package com.karson.admin.controller;

import com.karson.common.request.MenuRequest;
import com.karson.common.response.CommonResult;
import com.karson.common.response.MenusResponse;
import com.karson.common.util.RedisUtil;
import com.karson.service.service.SystemMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/menu")
@Tag(name = "路由管理接口")
public class MenuController {
    @Autowired
    private SystemMenuService systemMenuService;


    @GetMapping("/getMenu")
    @Operation(summary = "获取后台用户可访问目录")
    private CommonResult<Map<String,List<MenusResponse>>> getMenu() {
        List<MenusResponse> menuList = systemMenuService.getMenu();
        Map<String, List<MenusResponse>> map = new HashMap<>();
        map.put("menuList", menuList);
        return CommonResult.success(map);
    }
    @PostMapping("/save")
    @Operation(summary = "新增菜单")
    private CommonResult<String> save(@RequestBody @Validated MenuRequest menuRequest) {
       boolean flag = systemMenuService.saveMenu(menuRequest);
       if (flag) {
           return CommonResult.success();
       }else {
           return CommonResult.validateFailed(" 不能重复添加相同名字或路径的菜单");
       }
    }
    @PostMapping("/update")
    @Operation(summary = "修改菜单")
    private CommonResult<String> update(@RequestBody @Validated MenuRequest menuRequest) {
        if (systemMenuService.edit(menuRequest)){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }
    @Operation(summary = "删除菜单")
    @PostMapping("delete/{id}")
    public CommonResult<String> delete(@PathVariable(value = "id") Integer id) {
        if (systemMenuService.deleteById(id)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }
    @GetMapping("/cache/tree")
    @Operation(summary = "获取菜单缓存树")
    public CommonResult<Map<String,List<MenusResponse>>> getCacheTree() {
        List<MenusResponse> cacheTree = systemMenuService.getCacheTree();
        Map<String, List<MenusResponse>> map = new HashMap<>();
        map.put("menuList", cacheTree);
        return CommonResult.success(map);
    }

}
